<template>
  <div class="page-wrap">
    <el-card shadow="never">
      <div class="toolbar">
        <el-input v-model="filters.search" placeholder="搜索姓名/手机号" clearable class="w-260" />
        <el-select v-model="filters.tier" placeholder="等级" clearable class="w-160">
          <el-option v-for="t in tierRules" :key="t.key" :label="t.name" :value="t.key" />
        </el-select>
        <el-button type="primary" @click="openAdd">新增会员</el-button>
        <el-button @click="exportCsv">导出</el-button>
      </div>

      <div class="stats">
        <el-statistic title="会员数" :value="totalMembers" />
        <el-statistic title="总储值" :value="totalBalance" />
        <el-statistic title="总积分" :value="totalPoints" />
      </div>

      <el-table :data="pagedList" border stripe>
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="phone" label="手机号" width="140" />
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="{ row }">{{ genderMap[row.gender] || '未知' }}</template>
        </el-table-column>
        <el-table-column prop="tier" label="等级" width="120">
          <template #default="{ row }">{{ tierName(row.tier) }}</template>
        </el-table-column>
        <el-table-column prop="points" label="积分" width="100" />
        <el-table-column prop="balance" label="储值" width="100" />
        <el-table-column prop="lastVisit" label="最近到店" width="140" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="openEdit(row)">编辑</el-button>
            <el-button size="small" @click="openRecharge(row)">充值</el-button>
            <el-button size="small" @click="openPoints(row)">积分调整</el-button>
            <el-button size="small" type="danger" @click="onDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next, jumper"
        :page-size="page.size"
        :total="dataList.length"
        v-model:current-page="page.index"
      />
    </div>

    <!-- 新增/编辑 -->
    <el-dialog v-model="editVisible" :title="editForm.id ? '编辑会员' : '新增会员'" width="520px">
      <el-form :model="editForm" :rules="rules" ref="editRef" label-width="90px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="editForm.gender">
            <el-option label="男" value="M" />
            <el-option label="女" value="F" />
            <el-option label="未知" value="U" />
          </el-select>
        </el-form-item>
        <el-form-item label="生日">
          <el-date-picker v-model="editForm.birthday" type="date" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="等级">
          <el-select v-model="editForm.tier">
            <el-option v-for="t in tierRules" :key="t.key" :label="t.name" :value="t.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="积分">
          <el-input-number v-model="editForm.points" :min="0" />
        </el-form-item>
        <el-form-item label="储值">
          <el-input-number v-model="editForm.balance" :min="0" :precision="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editVisible=false">取消</el-button>
        <el-button type="primary" @click="onSave">保存</el-button>
      </template>
    </el-dialog>

    <!-- 充值 -->
    <el-dialog v-model="rechargeVisible" title="储值充值" width="420px">
      <el-form :model="rechargeForm" label-width="90px">
        <el-form-item label="会员">
          <span>{{ currentRow?.name }}（{{ currentRow?.phone }}）</span>
        </el-form-item>
        <el-form-item label="金额">
          <el-input-number v-model="rechargeForm.amount" :min="0" :precision="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="rechargeVisible=false">取消</el-button>
        <el-button type="primary" @click="onRecharge">确认</el-button>
      </template>
    </el-dialog>

    <!-- 积分调整 -->
    <el-dialog v-model="pointsVisible" title="积分调整" width="420px">
      <el-form :model="pointsForm" label-width="90px">
        <el-form-item label="会员">
          <span>{{ currentRow?.name }}（{{ currentRow?.phone }}）</span>
        </el-form-item>
        <el-form-item label="调整值">
          <el-input-number v-model="pointsForm.delta" :min="-999999" :max="999999" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="pointsVisible=false">取消</el-button>
        <el-button type="primary" @click="onAdjustPoints">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, computed, onMounted } from 'vue'
import { useMemberStore } from '@/stores/member.js'

const genderMap = { M: '男', F: '女', U: '未知' }

const store = useMemberStore()
const filters = reactive({ search: '', tier: '' })
const tierRules = computed(() => store.tierRules)
const dataList = computed(() => store.getFilteredMembers(filters))
const page = reactive({ index: 1, size: 10 })
const pagedList = computed(() => dataList.value.slice((page.index-1)*page.size, page.index*page.size))
const { totalMembers, totalBalance, totalPoints } = store

onMounted(() => {
  if (!store.members.length) store.initializeMembers()
})

const editVisible = ref(false)
const rechargeVisible = ref(false)
const pointsVisible = ref(false)
const currentRow = ref(null)
const editForm = reactive({ id: '', name: '', phone: '', gender: 'U', birthday: '', tier: 'normal', points: 0, balance: 0 })
const rechargeForm = reactive({ amount: 0 })
const pointsForm = reactive({ delta: 0 })
const editRef = ref()

const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
}

function tierName(key) {
  const t = tierRules.value.find(x => x.key === key)
  return t ? t.name : key
}

function openAdd() {
  Object.assign(editForm, { id: '', name: '', phone: '', gender: 'U', birthday: '', tier: 'normal', points: 0, balance: 0 })
  editVisible.value = true
}
function openEdit(row) {
  Object.assign(editForm, row)
  editVisible.value = true
}
function openRecharge(row) {
  currentRow.value = row
  rechargeForm.amount = 0
  rechargeVisible.value = true
}
function openPoints(row) {
  currentRow.value = row
  pointsForm.delta = 0
  pointsVisible.value = true
}

function onSave() {
  editRef.value.validate(valid => {
    if (!valid) return
    if (editForm.id) {
      store.updateMember(editForm.id, editForm)
    } else {
      store.addMember(editForm)
    }
    editVisible.value = false
  })
}
function onRecharge() {
  if (!currentRow.value) return
  store.rechargeBalance(currentRow.value.id, rechargeForm.amount)
  rechargeVisible.value = false
}
function onAdjustPoints() {
  if (!currentRow.value) return
  store.adjustPoints(currentRow.value.id, pointsForm.delta)
  pointsVisible.value = false
}
function onDelete(row) {
  store.deleteMember(row.id)
}

function exportCsv(){
  const rows = dataList.value.map(m => [m.name, m.phone, m.gender, m.tier, m.points, m.balance, m.createdAt, m.lastVisit])
  const headers = ['姓名','手机号','性别','等级','积分','储值','创建日期','最近到店']
  const csv = [headers.join(','), ...rows.map(r => r.join(','))].join('\n')
  const blob = new Blob(['\ufeff' + csv], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  const url = URL.createObjectURL(blob)
  link.href = url
  link.download = `会员数据_${new Date().toISOString().slice(0,10)}.csv`
  link.click()
  URL.revokeObjectURL(url)
}
</script>

<style scoped>
.page-wrap { padding: 16px; }
.toolbar { display: flex; gap: 12px; margin-bottom: 12px; align-items: center; }
.w-260 { width: 260px; }
.w-160 { width: 160px; }
.stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; margin-bottom: 12px; }
</style>


